import dva from '../dva';
import { DvaInstance } from 'dva-core';
import { ICreateDvaAppInstance, ICreateDvaAppOptions } from './interface';
import { createHashHistory as createHistory, History } from 'history';

export default function createDvaApp(options: ICreateDvaAppOptions) {
  const { routes, publicModels = [], loadModel, dvaOptions, hooks, root } = options;
  const history = dvaOptions && dvaOptions.history ? (dvaOptions.history as History<any>) : createHistory();
  const dvaRawApp: DvaInstance = dva({
    history,
    initialState: {},
  });
  //  history,
  // ...dvaOptions,
  const dvaApp = dvaRawApp as unknown as ICreateDvaAppInstance;
  dvaApp.getStore = () => dvaRawApp._store;
  dvaApp.getModels = () => dvaRawApp._models;
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  dvaApp.router(require('./router').default(routes, publicModels, loadModel, hooks, root));
  dvaApp.history = history;
  dvaApp.setupModels = () => {
    const context = require.context('@/models', true, /\.ts/);
    context.keys().forEach((k) => {
      dvaApp.model(context(k).default);
    });
  };

  return dvaApp;
}
